<!--
 * @Author: Bonnie
 * @Date: 2021-12-03 14:34:54
 * @LastEditTime: 2021-12-03 15:13:59
 * @LastEditors: Bonnie
 * @Description: 
 * @FilePath: /public_demo/src/views/scroll_into_view/index.vue
-->
// 将元素滚动到可视区域
<template>
  <div class="box-sizing p10 scroll-container">
    <em>下面的列表，在3s后将会把第15个元素滚动到可视区域</em>
    <div>
      <input :value="value" @input="inputHandle" />
      <span @click="toScroll">scroll</span>
      点击使得该元素滚动到可视区域
    </div>
    <ul class="scroll-wrapper">
      <li v-for="(item,index) in list" :id="index+1" :key="index">{{item}}</li>
    </ul>
    <div class="mt10">
      知识点：
      <em class="em-hover underline cursor-pointer" @click="toApi">scrollIntoView</em>
      <p>scrollIntoView()方法会滚动元素的父容器，使被调用scrollIntoView()的元素对用户可见</p>
    </div>
  </div>
</template>
<script>
export default {
  name: "",
  components: {},
  props: [],
  data() {
    return {
      value: 14,
      list: []
    };
  },
  created() {},
  mounted() {
    let list = [];
    for (let i = 1; i <= 30; i++) {
      list.push(i);
    }
    this.list = list;
    setTimeout(() => {
      this.scrollHandle(14);
    }, 3000);
  },
  methods: {
    toApi() {
      window.open(
        "https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoView",
        "_blank"
      );
    },
    scrollHandle(index) {
      let ele = document.getElementById(index);
      if (!ele) return;
      ele.scrollIntoView({ block: "center", behavior: "smooth" });
    },
    toScroll() {
      let index = this.value;
      let list = this.list;
      if (list.includes(index)) {
        this.scrollHandle(index);
      } else {
        alert("输入的内容不存在");
      }
    },
    inputHandle(e) {
      this.value = Number(e.target.value);
    }
  }
};
</script>
<style lang='scss' scoped>
.scroll-container {
  width: 700px;
  height: 100%;
  input {
    outline: none;
    border: 1px solid #b2b6b6;
    text-indent: 12px;
    width: 100px;
    height: 31px;
    line-height: 21px;
    border-radius: 8px;
  }
  span {
    display: inline-block;
    width: 70px;
    line-height: 30px;
    text-align: center;
    border: 1px solid #b2b6b6;
    border-radius: 8px;
    background-color: #8341ff;
    color: white;
    cursor: pointer;
  }
  ul {
    margin-top: 50px;
    height: 400px;
    border-radius: 12px;
    border: 1px solid #b2b6b6;
    overflow: auto;
    li {
      line-height: 50px;
      border-bottom: 1px solid #8341ff;
      padding-left: 50px;
    }
  }
}
</style>